/* 2008 by Johannes Fahrenkrug
  http://springenwerk.com
*/

var RED = 'red';
var GREEN = 'green';
var BLUE = 'blue';

var globalViewer = {};
var globalOwner = {};
var ownerColor = '';

var DEBUG = false;

function saveOwnerColor(color) {
  if (isViewerOwner()) {
    ownerColor = color;
    refreshOwnerColorMenu();
    var req = opensocial.newDataRequest();
    req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, 'color', color));
    req.send(onSaveColor);
  }
}

function onSaveColor(data) {
    if (DEBUG) console.log(data);
}


function loadData() {
  var req = opensocial.newDataRequest();
  var params = {};
  params[opensocial.DataRequest.PeopleRequestFields.MAX] = 1000;
  params[opensocial.DataRequest.PeopleRequestFields.FILTER] = opensocial.DataRequest.FilterType.HAS_APP;
  req.add(req.newFetchPersonRequest('OWNER'), 'owner');
  req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
  req.add(req.newFetchPeopleRequest('OWNER_FRIENDS', params), 'ownerFriends');
  req.add(req.newFetchPersonAppDataRequest('OWNER', 'color'), 'owner_color');
  req.add(req.newFetchPersonAppDataRequest('OWNER_FRIENDS', 'color'), 'owner_friends_color');
  req.send(onLoadData);
}

function refreshOwnerColorMenu() {
  var colors = {'red': 0, 'green': 0, 'blue': 0};
  var html = [];
  
  html.push('<h3>Select Your Color:</h3>');

  for (var currentColor in colors) {
    html.push('<div class="shadow');
    if (currentColor == ownerColor) {
      html.push('-selected');
    }
    html.push('"><div style="background-color: ');
    html.push(currentColor);
    html.push('; cursor: pointer"" onclick="saveOwnerColor(\'');
    html.push(currentColor);
    html.push('\')"></div></div>');
  }
  html.push('<div style="clear: both;"></div>');
  
  document.getElementById('set_color_box').innerHTML = html.join('');
}

function onLoadData(data) {
  var owner = globalOwner = data.get('owner').getData();    
  var viewer = globalViewer = data.get('viewer').getData();
  var ownerFriends = data.get('ownerFriends').getData();
  var ownerColorData = data.get('owner_color').getData();
  var ownerFriendsColorData = data.get('owner_friends_color').getData();  
  ownerColor = (ownerColorData[owner.getId()] != null ? ownerColorData[owner.getId()]['color'] : '');
  
  if (DEBUG) console.log(ownerColor);
  
  var colors = {'red': 0, 'green': 0, 'blue': 0};
  
  if (isViewerOwner()) {
    refreshOwnerColorMenu();
  }
  
  if (DEBUG) console.log(ownerFriends);
  
  ownerFriends.each(function(friend) {
    var friendData = ownerFriendsColorData[friend.getId()];
    if (friendData) {
      colors[friendData['color']] += 1;
    }
  });
  
  if (DEBUG) console.log(colors);
  if (DEBUG) console.log(buildColorCode(colors));
  
  document.getElementById('color_index').innerHTML = '<h3>My Friends\' Color Index:</h3><div class="shadow"><div style="width:150px; height:50px; background-color:' + buildColorCode(colors) + '"></div></div>';
}

function buildColorCode(colors) {
  var total = colors['red'] + colors['green'] + colors['blue'];
  var r = Math.floor((255 / total) * colors['red']);
  var g = Math.floor((255 / total) * colors['green']);
  var b = Math.floor((255 / total) * colors['blue']);
  
  return '#' + decToHex(r) + decToHex(g) + decToHex(b);
}

function decToHex(dec) {
  var CHARARRAY="0123456789ABCDEF";
  var base = 16;
  var first = 0;
  var second = 0;
  
  first = dec % base;
  dec = dec - first;
  second = ( dec / base ) % base;
  
  return '' + CHARARRAY[second] + CHARARRAY[first]; 
}

function isViewerOwner() {
    try {
        if (globalViewer.getId() != null && globalOwner.getId() != null && globalViewer.getId() == globalOwner.getId()) {
            return true;
        } else {
            return false;
        }
    } catch(e) {
        return false;
    }
}

function init() {
  loadData();
}
